#include "include.h"
#include <PubSubClient.h>

PubSubClient mqtt_client(client);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE	(50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

/**
 * 配置mqtt
*/
void setup_mqtt_client(void){
    mqtt_client.setServer(mqtt_config_parameter.ip_add.c_str(), mqtt_config_parameter.ip_port.toInt());
    mqtt_client.setCallback(mqtt_callback_function);
}

/**
 * 检查是否连接
*/
bool query_mqtt_connect(void){
    return mqtt_client.connected();
}

/**
 * mqtt 客户端一直运行
*/
void mqtt_loop() {
    mqtt_client.loop();
    if(mqtt_config_parameter.topic != ""){
        if(mqtt_config_parameter.msg_status_type == "0"){
            mqtt_client.subscribe(mqtt_config_parameter.topic.c_str());
        }
        else {
            mqtt_client.publish(mqtt_config_parameter.topic.c_str(), mqtt_config_parameter.msg.c_str());
        }
        mqtt_config_parameter.topic = "";
    }
}

/**
 * 收到消息反馈
*/
void mqtt_callback_function(char* topic, byte* payload, unsigned int length) {
    String msg = "";
    msg.concat(topic);
    msg.concat('-');
    for (int i = 0; i < length; i++) {
        msg.concat((char)payload[i]);
    }
    system_status.client_CallBack_msg = msg;
}

/**
 * 重连
*/
void mqtt_server_reconnect() {
    if(system_status.net_status > 0){
        setup_mqtt_client();
        String client_Id = mqtt_config_parameter.client_Id;
        String user_name = mqtt_config_parameter.user_name; 
        String user_pwd = mqtt_config_parameter.user_pwd;
        lastMsg_time = millis();
        mqtt_client.connect(client_Id.c_str(), user_name.c_str(), user_pwd.c_str());
        while (!mqtt_client.connected()) {
            delay(500);
            long now = millis();
            if (now - lastMsg_time > 10000) {
                /*  用户输出*/
                user_serial_print("error-parameter\r\n");
                return ;
            }
        }
    }
}
